package com.tticar.invmanager.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.invmanager.api.service.IDeliveryOrderForStaffClient;
import com.tticar.invmanager.common.Enum.CodeType;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.entity.*;
import com.tticar.invmanager.entity.vo.SkuReturnToPage;
import com.tticar.invmanager.mapper.MMaterielTticarMapper;
import com.tticar.invmanager.service.*;
import com.tticar.invmanager.tticar.entity.GoodsOrder;
import com.tticar.invmanager.tticar.service.IGoodsOrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author chengxy
 * @date 2018/11/6 9:15
 * 员工端、天天爱车后台发货扣除仓储库存
 */
@Service("deliveryOrderForStaffClientImpl")
public class DeliveryOrderForStaffClientImpl implements IDeliveryOrderForStaffClient{
    @Autowired
    private ICodeCounterService codeCounterService;
    @Autowired
    private IRepositoryCountService repositoryCountService;
    @Autowired
    private IGoodsOrderService goodsOrderService;
    @Autowired
    private MMaterielTticarMapper mMaterielTticarMapper;
    @Autowired
    private IOutRepositoryDetailService outRepositoryDetailService;
    @Autowired
    private ISysTenantService sysTenantService;
    @Autowired
    private IMMaterielService materielService;
    @Autowired
    private IMMaterielSkuService materielSkuService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deliveryGoodsByStaffClient(String goodsOrderId) {
        GoodsOrder goodsOrder = goodsOrderService.selectById(goodsOrderId);

        if (StringUtils.isBlank(goodsOrderId)) {
            throw new MyServiceException("参数订单号不能为空");
        }
        //查询该笔订单下 有几个sku
        List<SkuReturnToPage> skuReturnToPages = goodsOrderService.queryGoodsDetailByOrderId(Long.valueOf(goodsOrderId));

        if (skuReturnToPages != null && skuReturnToPages.size() > 0 && skuReturnToPages.get(0).getStorageSkuId() == null) {
            Long tenantId = mMaterielTticarMapper.queryTenantId(skuReturnToPages.get(0).getGoodsId(), skuReturnToPages.get(0).getSkuValue());
            if (tenantId == null) {
                return;
            }
            /**
             * 如果该租户不需要关联仓储存货，直接跳出
             * */

            Wrapper wrapper = new EntityWrapper<>();
            wrapper.eq("need_relative_inv", 1);
            List<SysTenant> sysTenants = sysTenantService.selectList(wrapper);
            for (SysTenant sys : sysTenants) {
                if (sys.getId().equals(tenantId)) {
                    return;
                }
            }
            String ckCode = codeCounterService.getOrderCodeByTenantId(CodeType.CK, tenantId);
            for (SkuReturnToPage skus : skuReturnToPages) {
                List<Map> aLong = mMaterielTticarMapper.queryRelativeInvMaterielId(skus.getGoodsId(), skus.getSkuValue());
//                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession().setAttribute("_tenant_id_",tenantId);
//                request.setAttribute("_tenant_id_",tenantId);
                //判断 订单店铺是否是关联店铺 如果不是跳出
                List<Long> longs =  mMaterielTticarMapper.queryTticarStoreList();
                if (longs == null || !longs.contains(goodsOrder.getSellStoreId())) {
                    return;
                }
                //如果未关联存货，抛异常
                if (aLong == null || aLong.size() < 1) {
                    throw new MyServiceException("该商品未关联仓储，无法发货");
//                    return;
                }
                //如果关联了 查询默认出库
                for (int z = 0; z < aLong.size();z++){
                    List<RepositoryCount> repositoryCounts = repositoryCountService.queryOutRepositoryByTenantId((Long) aLong.get(z).get("skuId"),tenantId);

                    Integer totalNum = 0;
                    int count = skus.getCount() * (int) aLong.get(z).get("comboCount");
                    for (RepositoryCount rep : repositoryCounts ) {

                        Long wearhouseId = Long.valueOf(rep.getWearhouseId());
                        Integer num = Integer.valueOf(rep.getCount() > count?count:rep.getCount());
                        totalNum += num;
                        OutRepositoryDetail outDetail = new OutRepositoryDetail();
                        outDetail.setSkuId((Long) aLong.get(z).get("skuId"));
                        outDetail.setCode(ckCode);
                        outDetail.setBuszId(Long.valueOf(goodsOrderId));
                        outDetail.setWearhouseId(wearhouseId);
                        outDetail.setType(4);
                        outDetail.setCount(num);
                        outDetail.setStatus(0);
                        outDetail.setCtime(new Date());
                        Date now = new Date();
                        now.setHours(0);
                        now.setMinutes(0);
                        now.setSeconds(0);
                        outDetail.setOrderTime(now);
                        outDetail.setRemark("天天爱车平台:订单发货出库。");
                        outDetail.setUsername("admin");
                        outDetail.setTenantId(tenantId);
                        //生成出库单
                        if (num > 0) {
                            outRepositoryDetailService.insertOrUpdate(outDetail);
                            //更新库存
                            repositoryCountService.updateRepositoryCountByTenantId((Long) aLong.get(z).get("skuId"), wearhouseId, num * -1, tenantId);
                        }
                        if (totalNum >= count) {
                            break;
                        }

                    }

                    if (totalNum < count) {
                        MMaterielSku mMaterielSku = materielSkuService.selectNotTenantId(Long.valueOf(aLong.get(z).get("skuId").toString()),tenantId);
                        if (mMaterielSku != null) {
                            MMateriel mMateriel = materielService.selectNotTenantId(mMaterielSku.getMid(),tenantId);
                            throw new MyServiceException(mMateriel.getName() + mMaterielSku.getSkus() + ",库存不足");
                        } else {
                            throw new MyServiceException("商品库存不足");
                        }



                    }

                    }

                }
            //是供应商代下单的订单
        }else if (skuReturnToPages != null && skuReturnToPages.size() > 0 && skuReturnToPages.get(0).getStorageSkuId() != null){
            Long tenantId = mMaterielTticarMapper.queryTenantIdByMaterielSkuId(skuReturnToPages.get(0).getStorageSkuId());
            Wrapper wrapper = new EntityWrapper<>();
            //不需要关联仓储的直接跳出
            wrapper.eq("need_relative_inv", 1);
            List<SysTenant> sysTenants = sysTenantService.selectList(wrapper);
            for (SysTenant sys : sysTenants) {
                if (sys.getId().equals(tenantId)) {
                    return;
                }
            }

            String ckCode = codeCounterService.getOrderCodeByTenantId(CodeType.CK, tenantId);

            for (SkuReturnToPage skus : skuReturnToPages) {
                List<RepositoryCount> repositoryCounts = repositoryCountService.queryOutRepositoryByTenantId(skus.getStorageSkuId(),tenantId);

                Integer totalNum = 0;
                int count = skus.getCount();
                for (RepositoryCount rep : repositoryCounts ) {
                    Long wearhouseId = Long.valueOf(rep.getWearhouseId());
                    Integer num = Integer.valueOf(rep.getCount() > count?count:rep.getCount());
                    totalNum += num;
                    OutRepositoryDetail outDetail = new OutRepositoryDetail();
                    outDetail.setSkuId(skus.getStorageSkuId());
                    outDetail.setCode(ckCode);
                    outDetail.setBuszId(Long.valueOf(goodsOrderId));
                    outDetail.setWearhouseId(wearhouseId);
                    outDetail.setType(4);
                    outDetail.setCount(num);
                    outDetail.setStatus(0);
                    outDetail.setCtime(new Date());
                    Date now = new Date();
                    now.setHours(0);
                    now.setMinutes(0);
                    now.setSeconds(0);
                    outDetail.setOrderTime(now);
                    outDetail.setRemark("天天爱车平台:订单发货出库。");
                    outDetail.setUsername("admin");
                    outDetail.setTenantId(tenantId);
                    if (num > 0) {
                        outRepositoryDetailService.insertOrUpdate(outDetail);
                        //更新库存
                        repositoryCountService.updateRepositoryCountByTenantId(skus.getStorageSkuId(), wearhouseId, num * -1, tenantId);
                    }
                    if (totalNum >= count) {
                        break;
                    }
                }
                if (totalNum < count) {
                    MMaterielSku mMaterielSku = materielSkuService.selectNotTenantId(Long.valueOf(skus.getStorageSkuId().toString()),tenantId);
                    if (mMaterielSku != null) {
                        MMateriel mMateriel = materielService.selectNotTenantId(mMaterielSku.getMid(),tenantId);
                        throw new MyServiceException(mMateriel.getName() + mMaterielSku.getSkus() + ",库存不足");
                    }else {
                        throw new MyServiceException("库存不足");
                    }


                }

            }


        }

    }
}
